<?php
require_once("../../../config.inc.php");
$isReloadable = false;
require_once("../../../app/_inc/include.php");
require_once("./_inc/entityFunction.php");

$errMsg = sxREQ('msg');
$objUser = $_SESSION[USEROBJ];
$aDataArea = $objUser->getDataArea();
$entity = (sxREQ('ent')=='')?sxREQ('entity'):sxREQ('ent');
$dataArea = substr($entity,0,4);
$sCondDataArea = "";
$indef_article='a';
if($entity==''){
	$url = $_SESSION[USEROBJ]->getHistory(0, true)."&msg=".urlencode(_t("missing entity."));
	serverRedir($url);
}
if($dataArea==''){
	$url = $_SESSION[USEROBJ]->getHistory(0, true)."&msg=".urlencode(_t("missing subject-area."));
	serverRedir($url);
}
if(!isset($aDataArea[$dataArea])){
	$url = $_SESSION[USEROBJ]->getHistory(0, true)."&msg=".
		urlencode(_t("User disabled for subject-area '%s'",$dataArea));
	serverRedir($url);
}
$sSQL = "SELECT subject_area FROM subject_area " .
		" WHERE data_area='$dataArea' " .
		" ORDER BY subject_area"; 
$objSDAO->query($sSQL,"SA");
while($row=$objSDAO->fetch('SA')) {
	$aSA['sa_'.$row['subject_area']] = false;
}

if(sxREQ("reqtype")==''){
	$new_entity = substr($entity,5);
	$sSQL = "SELECT e.*, sa.subject_area FROM entity e " .
			"  LEFT JOIN subject_area_entity sa ON sa.entity = e.entity " .
			"  WHERE e.entity='$entity' " .
			"  ORDER BY sa.subject_area ";
	$objSDAO->query($sSQL,"sel");
	if (!$row = $objSDAO->fetch("sel")) {
		$url = $_SESSION[USEROBJ]->getHistory(0, true)."&msg=".urlencode(_t("missing entity ",$entity));
		serverRedir($url);
	}
	$data_area = $row["data_area"];
	$description = $row["description"];
	$indef_article = $row["indef_article"];
	$note = $row["note"];
	$physical_param = $row["physical_param"];
	$supertype_entity = $row["supertype_entity"];
	$discrim_attribute = $row["discrim_attribute"];
	$discrim_value = $row["discrim_value"];
	while($row) {
		if ($row['subject_area']!='') {
			$aSA['sa_'.$row['subject_area']] = true;	
		}
		$row = $objSDAO->fetch("sel");
	}
} else {
	if(sxREQ("reqtype")=='save'){
		$errMsg .= entUpdate();
	}
	$data_area = sxREQUEST("data_area");
	$new_entity = sxREQUEST("new_entity");
	$description = sxREQUEST("description");
	$indef_article = sxREQUEST("indef_article");
	$supertype_entity = sxREQUEST("supertype_entity");
	$discrim_attribute = sxREQUEST("discrim_attribute");
	$discrim_value = sxREQUEST("discrim_value");
	$note = sxREQUEST("note");
	$physical_param = sxREQUEST("physical_param");
	foreach($_REQUEST as $nome => $val) {
		if (substr($nome,0,3) != 'sa_') continue;
		$aSA[$nome] = true;
	}
}
//output HTML
$aOpz = array("kMenu"=>'dam', "isReloadable"=>false);
echo(headerHTML($aOpz));
?>
<script language="JavaScript" type="text/javascript" src="../../_jsc/form.js"></script>  
<script language="JavaScript" type="text/javascript">
	function objFrmSave(){
		var objFrm = document.getElementById("objFrm");
		var objMessArea =  document.getElementById("messArea");
		var errMsg = "";
		if(errMsg == ""){
			objFrm.reqtype.value = 'save';
			objFrm.submit();cntp_type
		}else{
			objMessArea.innerHTML = errMsg;
		}		
	}
</script>
  
<?php
echo(bodyHTML($aOpz));
$sSQL = "SELECT description FROM data_area WHERE data_area = '$dataArea' ";
$query = $objSDAO->query($sSQL,'da');
if (!$rowDA = $objSDAO->fetch('da')) {
	$url = $_SESSION[USEROBJ]->getHistory(-1, true)."&msg=".urlencode(_t("data-area '%s' not found",$dataArea));
	serverRedir($url);
}
echo("<table width=\"100%\" cellpadding=\"03\" cellspacing=\"0\">");
echo("<tr>" .
		"<td class=\"labl01\" width='10%'>Data-Area: </td>" .
		"<td class=\"text01\" width='90%'><a class='text01' href='../area/dataAreaView.php?da=$dataArea&xsn=".XSN.
			"' title='"._t('Data-Area view')."'>$dataArea</a>' - ".
			sxHE($rowDA['description'])."</td></tr>");
echo("</table>");
//form 
echo("<form name=\"objFrm\" id=\"objFrm\" action=\"entityMod.php\" method=\"POST\">");
echo("<input type=\"hidden\" name=\"reqtype\" id=\"reqtype\" value=\"...\">");
echo("<input type=\"hidden\" name=\"entity\" id=\"entity\" value=\"$entity\">");
echo("<input type=\"hidden\" name=\"data_area\" id=\"data_area\" value=\"$dataArea\">");
echo("<input type=\"hidden\" name=\"xsn\" id=\"xsn\" value=\"".XSN."\">");
//output comandi
$aCmd = array("saveEnt"=>array("pag"=>"javascript:objFrmSave()",
										"title"=>_t("save"),
										"text"=>_t("save"),
										"perm"=>"M"),
					"back"=>array("pag"=>$objUser->getHistory(0,false),
										"title"=>'cancel',
										"text"=>'cancel',
										"perm"=>"R")
				);
echo(commandsHTML($aCmd));	
echo("<table class='tabl01' width=\"100%\" cellpadding=\"3\" cellspacing=\"2\">\n");
echo("<tr>" .
			"<td class=\"titl01\" colspan=\"2\">"._t("Entity")."</td>" .
		"</tr>\n");
echo("<tr>" .
			"<td class=\"labl01\">"._t("entity")."</td>" .
			"<td class=\"text01\">".
			"<input type='text' class='inpt01' name='new_entity' value=\"$new_entity\" size='30' maxlength='32'>".
			"</td>" .
		"</tr>\n");
echo("<tr>" .
			"<td class=\"labl01\">"._t("Description")."</td>");
echo("<td class=\"text01\">");
$aVal = array("a"=>"a","an"=>"an");
echo getHTMLSelect('indef_article', $aVal, $indef_article);			
echo("<input class=\"inpt01\" type=\"text\" name=\"description\" id=\"description\" maxlength=\"80\" size=\"80\" value=\"".sxHE($description)."\"></td>" .
		"</tr>\n");
		
echo("<tr>" .
			"<td class=\"labl01\">Supertype entity</td>");
echo("<td class=\"text01\">");
$aSTEnt = array(""=>"-- not a sub-type --");
$sSQL = "SELECT e.* FROM entity e " .
		"  WHERE e.entity<>'$entity' AND data_area = '$data_area'" .
		"  ORDER BY e.entity ";
$objSDAO->query($sSQL,"selSTE");
while($rowSTE = $objSDAO->fetch("selSTE")) {
	$aSTEnt[$rowSTE['entity']] =  $rowSTE['entity']." - ".$rowSTE['description'];
}
$aOptSTE = array('onChange'=>"document.objFrm.submit();");
echo getHTMLSelect('supertype_entity', $aSTEnt, $supertype_entity,$aOptSTE);			
echo("</td></tr>\n");
//dbg_("supertype_entity=".$supertype_entity);
if ($supertype_entity!='') {
	echo("<tr>" .
				"<td class=\"labl01\">Discriminating attribute</td>");
	echo("<td class=\"text01\">");
	$aSTAtt = array(""=>"-- select an attribute --");
	$sSQL = "SELECT * FROM attribute WHERE entity = '$supertype_entity' " .
			"  ORDER BY sequence ";
	//dbg_("sql discr.attr=".$sSQL);
	$objSDAO->query($sSQL,"selSTAtt");
	while($rowSTAtt = $objSDAO->fetch("selSTAtt")) {
		$aSTAtt[$rowSTAtt['attribute']] =  $rowSTAtt['attribute']." - ".$rowSTAtt['description'];
	}
	echo getHTMLSelect('discrim_attribute', $aSTAtt, $discrim_attribute);			
	echo("</td></tr>\n");
			
	echo("<tr>" .
				"<td class=\"labl01\">Discriminating value</td>");
	echo("<td class=\"text01\">");
	echo getHTMLText('discrim_value', 40,0,$discrim_value);			
	echo("</td></tr>\n");
}		
echo("<tr>" .
			"<td class=\"labl01\">"._t("Subject-Area")."</td>".
			"<td class=\"text01\">\n");
if (is_array($aSA)) {			
	foreach($aSA as $nome => $checked) {
		echo("<input class=\"inpt01\" type=\"checkbox\" name=\"$nome\" id=\"$nome\" value=\"Y\" ".
			(($checked)?'CHECKED':'').">" .substr($nome,3)."<br>\n");
	}
}
echo("</td>" .
		"</tr>\n");
echo("<tr>" .
			"<td class=\"labl01\">"._t("Note")."</td>" .
			"<td class=\"text01\"><textarea class=\"inpt01\" name=\"note\" id=\"note\" cols=\"80\" rows=\"3\">".sxHE($note)."</textarea></td>" .
		"</tr>\n");
echo("<tr>" .
			"<td class=\"labl01\">"._t("Physical parameters")."</td>" .
			"<td class=\"text01\"><textarea class=\"inpt01\" name=\"physical_param\" id=\"physical_param\" cols=\"80\" rows=\"3\">".sxHE($physical_param)."</textarea></td>" .
		"</tr>\n");

echo("</table>");
echo("</table>");
echo(commandsHTML($aCmd));
echo("</form>");
echo("</td>\n</tr>\n</table>\n");
echo(footerHTML());
exit();

function entUpdate(){
	global $objSDAO;
	$errMsg = "";
	$_REQUEST["new_entity"] = strtolower(trim($_REQUEST["new_entity"]));
	if(!isset($_REQUEST["new_entity"]) || $_REQUEST["new_entity"] == "")
		$errMsg .= _t("L'entity &egrave; obbligatoria");
	if(!isset($_REQUEST["data_area"]) || $_REQUEST["data_area"] == "")
		$errMsg .= _t("Name missing");
	if(ereg("[^a-z0-9_]",$_REQUEST["new_entity"]))
		$errMsg .= _t("name charachters not allowed").".<br>";
	if(strpos($_REQUEST["new_entity"], " ") !== false)
		$errMsg .= _t("Name - space not allowed").".<br>";
	//controllo che il nuovo nome dell'entity, se diverso, non esista gi@
	if (substr($_REQUEST["entity"],5) != $_REQUEST["new_entity"]) {
		$sSQL = "SELECT count(*) as numentity FROM entity " .
				" WHERE entity='".$_REQUEST["data_area"]."_".$_REQUEST["new_entity"]."'";
		$numEntity = 0;
		$objSDAO->query($sSQL,"test");
		$row = $objSDAO->fetch("test");
		if($row["numentity"] != 0)
			$errMsg .= _t("entity existing");
	}
	
	if (sxREQ('supertype_entity') != '') {
		if (sxREQ('discrim_attribute') == ''
			|| sxREQ('discrim_value') == '') {
				$errMsg .= "discriminating attribute/value missing<br>";
		}
		// check for same primary key in super-type and sub-type entity
		// TO DO
	}
	if (sxREQ('supertype_entity') == '' 
	&& (sxREQ('discrim_attribute') != ''
		|| sxREQ('discrim_value') != '')) {
			$errMsg .= "discriminating attribute/value for sub-type entity only<br>";
	}
	
	if($errMsg != "")
		return $errMsg;

   if(trim($_REQUEST["description"])=="") $_REQUEST["description"]= substr($_REQUEST["new_entity"],5);
	$sSQL = "UPDATE entity SET " .
			" description='".addslashes(sxGPC($_REQUEST["description"]))."', " .
			" indef_article='".addslashes(sxGPC($_REQUEST["indef_article"]))."', " .
			" supertype_entity='".addslashes(sxGPC($_REQUEST["supertype_entity"]))."', " .
			" discrim_attribute='".addslashes(sxGPC($_REQUEST["discrim_attribute"]))."', " .
			" discrim_value='".addslashes(sxGPC($_REQUEST["discrim_value"]))."', " .
			" note='".addslashes(sxGPC($_REQUEST["note"]))."', " .
			" physical_param='".addslashes(sxGPC($_REQUEST["physical_param"]))."' " .
			" WHERE entity='".sxRAS("entity")."'";	
	$objSDAO->query($sSQL,"upd");
	//dbg_($sSQL);
	
	$sSQL = "DELETE FROM subject_area_entity WHERE entity='".sxRAS("entity")."'";	
	$objSDAO->query($sSQL,"upd");
	foreach($_REQUEST as $nome => $val) {
		if (substr($nome,0,3) != 'sa_') continue;
		$sSQL = "INSERT INTO subject_area_entity (data_area, subject_area, entity) VALUES (" .
				"'".substr(sxRAS("entity"),0,4)."', '".substr($nome,3)."', '".sxRAS("entity")."')";	
		$objSDAO->query($sSQL,"upd");			
	}
	
	if (substr($_REQUEST["entity"],5) != $_REQUEST["new_entity"]) {
		$sSQL = "UPDATE entity SET entity='".$_REQUEST["data_area"]."_".$_REQUEST["new_entity"]."'" .
			" WHERE entity='".addslashes(sxGPC($_REQUEST["entity"]))."'";	
		$objSDAO->query($sSQL,"upd");
		$sSQL = "UPDATE subject_area_entity SET entity='".$_REQUEST["data_area"]."_".$_REQUEST["new_entity"]."'" .
			" WHERE entity='".addslashes(sxGPC($_REQUEST["entity"]))."'";	
		$objSDAO->query($sSQL,"upd");
		$sSQL = "UPDATE attribute SET entity='".$_REQUEST["data_area"]."_".$_REQUEST["new_entity"]."'" .
			" WHERE entity='".addslashes(sxGPC($_REQUEST["entity"]))."'";	
		$objSDAO->query($sSQL,"upd");
		$sSQL = "UPDATE relationship SET parent_entity='".$_REQUEST["data_area"]."_".$_REQUEST["new_entity"]."'" .
			" WHERE parent_entity='".addslashes(sxGPC($_REQUEST["entity"]))."'";	
		$objSDAO->query($sSQL,"upd");
		$sSQL = "UPDATE relationship SET child_entity='".$_REQUEST["data_area"]."_".$_REQUEST["new_entity"]."'" .
			" WHERE child_entity='".addslashes(sxGPC($_REQUEST["entity"]))."'";	
		$objSDAO->query($sSQL,"upd");
		$sSQL = "UPDATE relationship_key SET parent_entity='".$_REQUEST["data_area"]."_".$_REQUEST["new_entity"]."'" .
			" WHERE parent_entity='".addslashes(sxGPC($_REQUEST["entity"]))."'";	
		$objSDAO->query($sSQL,"upd");
		$sSQL = "UPDATE relationship_key SET child_entity='".$_REQUEST["data_area"]."_".$_REQUEST["new_entity"]."'" .
			" WHERE child_entity='".addslashes(sxGPC($_REQUEST["entity"]))."'";	
		$objSDAO->query($sSQL,"upd");
		$sSQL = "UPDATE domain SET lookup_entity='".$_REQUEST["data_area"]."_".$_REQUEST["new_entity"]."'" .
			" WHERE lookup_entity='".addslashes(sxGPC($_REQUEST["entity"]))."'";	
		$objSDAO->query($sSQL,"upd");
	}
	logRecord("410", _t("Modificata l'entity")." '".addslashes(sxGPC($_REQUEST["data_area"]))."_".addslashes(sxGPC($_REQUEST["new_entity"]))."' "._t("nell'area dati")." '".addslashes(sxGPC(strtolower($_REQUEST["data_area"])))."'");
	//serverRedir("entityList.php?da=".$_REQUEST["data_area"]."&xsn=".XSN);
	$url = $_SESSION[USEROBJ]->getHistory(0, true);
	serverRedir($url);
	exit;
}
